//处理博客相关的路由

//导入外部模块
const { SuccessModel, ErrorModel}=require('../model/responseModel');
const {getBlogList, getBlogDetail,createNewBlog,updateBlog,deleteBlog}=require('../controllers/blog');


//博客路由控制函数
const handleBlogRoute=(req,res)=>{
    //获取请求参数和数据
    const method=req.method;
    const blogData=req.body;
    const id=req.query.id;
   
    //获取博客列表路由
    if(method==='GET'&&req.path==='/api/blog/list'){
        const author=req.query.auther||'';
        const keyword=req.query.keyword||'';
        const listDataPromise=getBlogList(author,keyword);//getList方法定义在controller下的blog.js中
        return listDataPromise.then((listData)=>{
            return new SuccessModel(listData);
        });
    }

    //获取博客详情路由
    if(method==='GET'&&req.path==='/api/blog/detail'){
        // const detailData=getBlogDetail(id);
        // return new SuccessModel(detailData);
        const detailDataPromise=getBlogDetail(id);
        return detailDataPromise.then(detailData=>{
            return new SuccessModel(detailData);
        })
    }

    //新建博客路由
    if(method==='POST'&&req.path==='/api/blog/new'){
        // const newBlogData=createNewBlog(blogData);
        // return new SuccessModel(newBlogData);
        const author='用户名';
        req.body.author=author;//这里用一个假数据代替登录后的作者名
        const newBlogDataPromise=createNewBlog(blogData);
        return newBlogDataPromise.then(newBlogData=>{
            return new SuccessModel(newBlogData);
        })
    }

    //更新博客路由
    if(method==='POST'&&req.path==='/api/blog/update'){
        // const updatedBlogData=updateBlog(id,blogData);
        const updatedBlogDataPromise=updateBlog(id,blogData);
        return updatedBlogDataPromise.then(updatedBlogData=>{
            if(updatedBlogData){
                return new SuccessModel('更新博客成功!');
            }else{
                return new ErrorModel('更新博客失败...');
            }
        });   
    }

    //删除博客路由
    if(method==='POST'&&req.path==='/api/blog/delete'){
        const author='用户名';
        const deleteBlogDataPromise=deleteBlog(id,author);
        deleteBlogDataPromise.then(deleteBlogData=>{
            if(deleteBlogData){
                return new SuccessModel('博客删除成功!');
            }else{
                return new ErrorModel('博客删除失败...');
            }
        });     
    }
};

module.exports = handleBlogRoute;